﻿/**
 * SlotDuino
 * 
 * Copyright (c) 2011/2012 Thiago Hummel Moreira, Ricardo Mizuuti, Rafael Mufato, Bruno Sakai, Andre Turina
 * 
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
using System;
using System.Data;
using System.Data.Objects;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using SlotDuino.DAL;
using SlotDuino.Util;

namespace SlotDuino.UI.Pages
{
    /// <summary>
    /// Interaction logic for ChampionshipCreate.xaml
    /// </summary>
    public partial class ChampionshipCreate : Page
    {
        #region Dependency properties
        public static readonly DependencyProperty ChampionshipProperty = DependencyProperty.Register("Championship", typeof(Championship), typeof(ChampionshipCreate));
        #endregion

        #region Private attributes
        private EntityContainer _context;
        #endregion

        #region Public properties
        public Championship Championship
        {
            get { return (Championship)GetValue(ChampionshipProperty); }
            set { SetValue(ChampionshipProperty, value); }
        }
        #endregion


        public ChampionshipCreate()
        {
            InitializeComponent();
        }
        
        private void Page_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            //Create the entity context
            _context = new EntityContainer();

            //Setup view sources
            var pilotsViewSource = (CollectionViewSource)FindResource("pilotsViewSource");
            pilotsViewSource.Source = GetAllPilots(_context);

            var templateViewSource = (CollectionViewSource)FindResource("templateViewSource");
            templateViewSource.Source = GetAllTemplate(_context);

            //Load times for template
            StartTimeTemplate(_context);

            //Always new
            Championship = new Championship();
            Championship.StartDate = DateTime.Today; //Avoid errors on conversion to datetime2 on DB
            Championship.EndDate = DateTime.Today; //Avoid errors on conversion to datetime2 on DB
            Championship.Name = txtName.Text;
            Championship.RaceTime = textToTime(int.Parse(txtRaceTime.Text), cmbRace.Text);
            Championship.QualifyingTime = textToTime(int.Parse(txtQualifyingTime.Text), cmbQualifyTime.Text);
            Championship.IntervalTime = textToTime(int.Parse(txtIntervalTime.Text), cmbInterval.Text);
            
            //Get a reference to viewSource (defined on the XAML)
            var viewSource = ((CollectionViewSource)(FindResource("enroll")));

            //Set Enrollment into Championship
            viewSource.Source = Championship.Enrollments;

            //Add the new instance to the context
            _context.AddToChampionships(Championship);

            //Focus first field
            txtName.Focus();

        }

        private IQueryable<ChampionshipTemplate> GetModel(EntityContainer context, string name)
        {
            IQueryable<ChampionshipTemplate> query;
            query = from p in context.ChampionshipTemplates select p;
            return query;
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            if (dataGrid.ItemsSource.OfType<Pilot>().Count() > 1)
            {

                try
                {
                    //This must come before the saveChanges, or else we will not know 
                    string msg = String.Format("Campeonato '{0}' criado com sucesso.", txtName.Text);

                    _context.SaveChanges();

                    Msg.ShowOk(msg);
                }
                catch (Exception ex)
                {
                    Msg.ShowError(ex.Message);
                }
            }
            else
            {
                Msg.ShowError("São necessários no mínimo dois piltos para criar um campeonato.");
            }
        }

        private void btnTemplateEdit_Click(object sender, RoutedEventArgs e)
        {

        }

        private void btnTemplateSave_Click(object sender, RoutedEventArgs e)
        {
            /*
            if (txt.Text != "" && txtQualifyingTime.Text != "" && txtRaceTime.Text != "" && txtIntervalTime.Text != "")
            {

                //Create the entity context
                _context = new EntityContainer();

                ChampionshipTemplate templ = new ChampionshipTemplate();

                templ.Name = txtNewTemplate.Text;
                templ.QualifyingTime = TimeSpan.Parse(txtQualifyingTime.Text);
                templ.RaceTime = TimeSpan.Parse(txtRaceTime.Text);
                templ.IntervalTime = TimeSpan.Parse(txtIntervalTime.Text);

                _context.AddToChampionshipTemplates(templ);
                _context.SaveChanges();
                //Focus first field
                txtName.Focus();

                Msg.ShowOk("Modelo " + templ.Name.ToString() + " salvo com sucesso!");

                IsEnable = false;

            }
            else {
                Msg.ShowError("Favor preencher todos os campos do novo modelo de campeonato !");
            }
            */
        }

        private IQueryable<Pilot> GetAllPilots(EntityContainer context)
        {
            return from p in context.People.OfType<Pilot>() select p;
        }

        private IQueryable<ChampionshipTemplate> GetAllTemplate(EntityContainer context, string search = null)
        {
            if (null != search)
            {
                return from p in context.ChampionshipTemplates where p.Name.Equals(search) select p;
            }
            else 
            {
                return from p in context.ChampionshipTemplates select p;
            }
        }

        private void StartTimeTemplate(EntityContainer context)
        {
            var templ = GetAllTemplate(context, cmbTemplates.Text).First();

            txtIntervalTime.Text = templ.IntervalTime.Minutes.ToString();
            txtRaceTime.Text = templ.RaceTime.Minutes.ToString();
            txtQualifyingTime.Text = templ.QualifyingTime.Minutes.ToString();
            cmbTemplates.Text = cmbTemplates.Text;

        }

        private void btnAddPilot_Click(object sender, RoutedEventArgs e)
        {   
            var enrollment = new ChampionshipEnrollment();
            var pilot = (Pilot)cmbPilots.SelectedItem;
            bool exists=false;

            //Test pilot already selected
            foreach (ChampionshipEnrollment p in dataGrid.Items)
            {
               if(p.Pilot.Equals(pilot)){ exists = true;}
            }

            if (exists)
            {
                Msg.ShowError("Piloto já registrado para este campeonato!");
            }
            else {
                enrollment.Pilot = pilot;
                Championship.Enrollments.Add(enrollment);
            }
            
             
            



        }

        private void btnRemove_Click(object sender, RoutedEventArgs e)
        {
            Championship.Enrollments.Remove((ChampionshipEnrollment)dataGrid.SelectedItem);
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            if (EntityState.Added != Championship.EntityState)
            {
                _context.Refresh(RefreshMode.StoreWins, Championship);
            }
            else
            {
                _context.DeleteObject(Championship);
            }

        }

        private TimeSpan textToTime(int value, string segOrMin)
        {
            TimeSpan ts = new TimeSpan();
            if (segOrMin == "minutos")
            {
                ts = new TimeSpan(0, value, 0);
            }
            if (segOrMin == "segundos")
            {
                ts = new TimeSpan(0, 0, value);
            }

            return ts;
        }

        private void btnNewPilot_Click(object sender, RoutedEventArgs e)
        {
            var data = new EntityContainer();

            Pilot pilot = (Pilot)cmbPilots.SelectedItem;
            if (null == pilot)
            {
                pilot = new Pilot();
                pilot.Name = cmbPilots.Text;
                pilot.Nickname = cmbPilots.Text;
                data.AddToPeople(pilot);
                data.SaveChanges();
                var pilotsViewSource = (CollectionViewSource)FindResource("pilotsViewSource");
                pilotsViewSource.Source = GetAllPilots(_context);
                cmbPilots.Text = pilot.Name;
                string msg = String.Format("Piloto '{0}' cadastrado com sucesso.", pilot.Name);
                Msg.ShowOk(msg);
            }
            else {
                Msg.ShowError("Piloto já cadastrado.");            
            }

            

        }

        private void dtpStart_LostFocus(object sender, RoutedEventArgs e)
        {
            dtpEnd.Text = dtpStart.Text;
        }

        private void dtpEnd_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void dtpEnd_LostFocus(object sender, RoutedEventArgs e)
        {
            if (Convert.ToDateTime(dtpEnd.Text) < Convert.ToDateTime(dtpStart.Text))
            {
                Msg.ShowError("Data final inferior a data inicial");
                dtpEnd.Text = dtpStart.Text;
                dtpEnd.Focus();
            }
        }


    }
}
